import React, { useState, useEffect } from 'react';
import { Modal,  message, Button, Tag } from 'antd';
import { connect, Dispatch } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import ProCard from '@ant-design/pro-card';
import { USER_LIST, USER_ADD, USER_UPDATE, USER_DELETE, USER_ROLE, USER_ASSIGN_ROLE, USER_RESET_PASS, 
  USER_UNMOUNT } from '@/actions/user';
import AButton from '@/components/SelfComp/AButton';
import AGrid, { AGridButtonCallBackModel } from '@/components/SelfComp/AGrid';
import { ConnectState } from '@/models/connect';
import { DataItem, FlagEnum } from '@/types/global';
import { UserItem, AssignRoleItem, AssignUserRoleData } from '@/types/user';
import { getItemValue } from '@/utils/commons';
import { AddUserModal, UpdateUserModal, AssignRoleModal, UserQueryForm } from './components';

interface UserListProps {
  dispatch: Dispatch;
  userList: UserItem[],
  pageSize: number;
  total: number,
  loading: boolean;
  addLoading: boolean;
  updateLoading: boolean;
  previewLoading: boolean;
  assignLoading: boolean;
  resetLoading: boolean;
  sexData: DataItem[];
  statusData: DataItem[];
}

const EMPTY: UserItem = {
  userId: '',
  userCode: '',
  userName: '',
  userStates: '',
  sex: '',
  email: '',
  telephone: '',
  mobile: '',
  seatNo: '',
  computerNo: '',
  loginTime: '',
  loginHost: '',
  virtualCode: ''
}

const EMPTY_ASSIGN_ROLE: AssignUserRoleData = {
  userId: '',
  allRoleData: [],
  assignedRoleData: []
}

/**
 * 用户管理
 */
const UserList: React.FC<UserListProps> = (props) => {
  // 新增弹窗
  const [addModalVisible, setAddModalVisible] = useState<boolean>(false);
  const [userFormData, setUserFormData] = useState<UserItem>(EMPTY);
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  // const [selectedRows, setSelectedRows] = useState<UserItem[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  // 查询表单
  const [queryParam, setQueryParam] = useState<UserItem>();
  // 默认为10
  const [pageSize, setPageSize] = useState<number>(10);
  const [assignRoleModalVisible, setAssignRoleModalVisible] = useState<boolean>(false);
  const [roleFormData, setRoleFormData] = useState<AssignUserRoleData>(EMPTY_ASSIGN_ROLE);
  const [flag, setFlag] = useState<FlagEnum>('edit');

  useEffect(() => {
    console.info('UserList.useEffect');
    // 查询本页面需所有参数
    const { pageSize, dispatch } = props;
    fetchAllUser(1, pageSize, queryParam);
    return () => {
      dispatch(USER_UNMOUNT({}));
    }
  }, []);

  const columns = [
    {
      title: '用户姓名',
      dataIndex: 'userName',
      width: 90
    },
    {
      title: '用户账号',
      dataIndex: 'userCode',
      width: 120
    },
    {
      title: '手机号码',
      dataIndex: 'mobile',
      width: 100
    },
    {
      title: '虚拟机账号',
      dataIndex: 'virtualCode',
      width: 100
    },
    {
      title: '电子邮箱',
      dataIndex: 'email',
      width: 150,
      ellipsis: true
    },
    {
      title: '电脑编号',
      dataIndex: 'computerNo',
      width: 80
    },
    {
      title: '座位号',
      dataIndex: 'seatNo',
      width: 80
    },
    {
      title: '性别',
      dataIndex: 'sex',
      width: 60,
      render: (text: string, record: UserItem, index: number) => sexFunc(record),
    },
    {
      title: '状态',
      dataIndex: 'userStates',
      width: 80,
      render: (text: string, record: UserItem, index: number) => userStatesFunc(record),
    }
  ];

  const sexFunc = (record: UserItem) => {
    const { sexData } = props;
    const { sex } = record;
    if (!sex) {
      return '';
    }
    const value = getItemValue(sexData, sex);
    return <Tag color='processing'>{value}</Tag>
  }

  const userStatesFunc = (record: UserItem) => {
    const { statusData } = props;
    const { userStates } = record;
    if (!userStates) {
      return '';
    }
    const value = getItemValue(statusData, userStates);
    if (userStates === '1') {
      return <Tag color='error'>{value}</Tag>;
    }
    return <Tag color='processing'>{value}</Tag>
  }

  /**
   * 查询满足条件的数据字典
   */
  const handleSubmitEx = (record: UserItem) => {
    console.info('UserList.handleSubmitEx');
    console.info(record);
    const queryParam = {
      ...record
    };
    // 查询条件保存起来，方便点击页码时使用
    // setState回调方法，保证先更新state
    setQueryParam(queryParam);
    fetchAllUser(1, pageSize, queryParam);
  }

  const handleReset = () => {
    // 是否清空表格
  }

  const openAddUserModal = () => {
    setAddModalVisible(true);
  }

  const handleAddModalOk = async (record: UserItem) => {
    // console.log(record);
    const { dispatch } = props;
    console.info(dispatch);
    const res = await dispatch(USER_ADD(record));
    console.info(res);
    if (res) {
      setAddModalVisible(false);
      fetchAllUser(1, pageSize, queryParam);
    }
  }

  const handleAddModalCancel = () => {
    setAddModalVisible(false);
  };

  const openUpdateUserModal = (record: UserItem[], flag: FlagEnum) => {
    // 表格选中内容
    // console.info('openUpdateUserModal');
    console.info(record);
    const row = record[0];
    setUserFormData(row);
    setFlag(flag);
    setUpdateModalVisible(true);
  }

  /**
   * 更新面板的确定事件
   * @param {*} record 更新表单
   */
  const handleUpdateModalOk = async (record: UserItem) => {
    // console.log('handleUpdateModalOk');
    // console.log(record);
    console.info(userFormData);
    if (flag === 'edit') {
      const { dispatch } = props;
      const res = await dispatch(USER_UPDATE(record));
      console.info(res);
      if (res) {
        setUserFormData(EMPTY);
        setUpdateModalVisible(false);
        fetchAllUser(1, pageSize, queryParam);
      }
    } else {
      setUserFormData(EMPTY);
      setUpdateModalVisible(false);
    }
  }

  const handleUpdateModalCancel = () => {
    setUserFormData(EMPTY);
    setUpdateModalVisible(false);
  };

  /**
   * 分页查询系统参数信息
   * @param {*} pageNum 页码
   * @param {*} pageSize 每页记录条数
   */
  const fetchAllUser = (pageNum: number, pageSize: number, queryParam?: UserItem) => {
    const { dispatch } = props;
    dispatch(USER_LIST({
      ...queryParam,
      pageSize,
      pageNum
    }));
  }

  /**
   * 删除用户，暂时只支持单笔删除
   * @param userId 用户id
   */
  const deleteUsers = async (userId: string) => {
    const { dispatch } = props;
    const res = await dispatch(USER_DELETE(userId));
    if (res) {
      dispatch(USER_LIST({
        ...queryParam,
        pageSize,
        pageNum: 1,
      }));
    }
  }

  /**
   * 处理按钮点击回调事件
   * @param {*} payload 数据包
   */
  const handleBtnCallBack = (callBackModel: AGridButtonCallBackModel<UserItem>) => {
    // console.log('handleBtnCallBack');
    // console.log(callBackModel);
    // btn 按钮
    // keys 表格勾选数组
    const { code } = callBackModel;
    // 新增
    if (code === 'add') {
      openAddUserModal();
      return;
    }
    // 修改
    if (code === 'edit') {
      const { rows } = callBackModel;
      openUpdateUserModal(rows, 'edit');
      return;
    }
    // 删除
    if (code === 'delete') {
      const { keys } = callBackModel;
      // 调用删除服务，删除勾选数据
      const userId = keys[0];
      deleteUsers(userId as string);
      return;
    }
    // 查看
    if (code === 'view') {
      const { rows } = callBackModel;
      openUpdateUserModal(rows, 'view');
      return;
    }
  }

  /**
   * 表格勾选回调函数
   * @param {*} rows 表格选中数据集合
   */
  const onSelectRow = (keys: React.Key[], rows: UserItem[]) => {
    // setSelectedRows(rows);
    setSelectedRowKeys(keys);
  };

  /**
   * 页码改变的回调，参数是改变后的页码及每页条数
   * @param page 改变后的页码，上送服务器端
   * @param pageSize 每页数据条数
   */
  const onPageNumAndSizeChange = (page: number, pageSize: number) => {
    console.log(page, pageSize);
    setPageSize(pageSize);
    fetchAllUser(page, pageSize, queryParam);
  };

  const renderLeftButton = () => {
    const { previewLoading, resetLoading } = props;
    return (
      <>
        <AButton type='primary' code='assignRole' pageCode='user-list' name='分配角色' onClick={openAssignRoleModal} loading={previewLoading} />
        <AButton danger code='resetPass' pageCode='user-list' name='重置密码' onClick={handleResetUserPassword} loading={resetLoading} />
      </>
    );
  }

  /**
   * 角色授权，打开角色授权窗口
   */
  const openAssignRoleModal = async () => {
    // 表格选中内容
    console.info('openAssignRoleModal');
    if (selectedRowKeys.length === 0) {
      message.warn('请先选择一条数据!');
      return;
    }
    if (selectedRowKeys.length > 1) {
      message.warn('只能选择一条数据!');
      return;
    }
    // 获取用户id
    const userId = selectedRowKeys[0];
    console.info('userId', userId);
    const { dispatch } = props;
    const res = await dispatch(USER_ROLE({
      userId
    }));
    if (res) {
      // 查询菜单权限树，并根据勾选角色ID对应已分配的权限
      // 这里试试dispatch的回调方法
      // 只有查询成功才会弹窗
      const { result } = res;
      const { allRoleData, assignedRoleData } = result;
      const roleFormData: AssignUserRoleData = {
        userId,
        allRoleData,
        assignedRoleData
      };
      setRoleFormData(roleFormData);
      setAssignRoleModalVisible(true);
    }
  }

  const handleAssignModalOk = async (record: AssignRoleItem) => {
    console.log('handleAssignModalOk');
    console.log(record);
    const { dispatch } = props;
    const res = await dispatch(USER_ASSIGN_ROLE(record));
    if (res) {
      setRoleFormData(EMPTY_ASSIGN_ROLE);
      setAssignRoleModalVisible(false);
    }
  }

  const handleAssignModalCancel = () => {
    setRoleFormData(EMPTY_ASSIGN_ROLE);
    setAssignRoleModalVisible(false);
  }

  const handleResetUserPassword = () => {
    if (selectedRowKeys.length <= 0) {
      message.warn('请至少选择一条数据!');
      return;
    }
    Modal.confirm({
      title: '重置确认',
      content: '确定重置选中用户密码？',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => resetUserPassword(selectedRowKeys),
      onCancel() {},
    });
    return;
  }

  const resetUserPassword = async (rows: React.Key[]) => {
    console.log('resetUserPassword');
    const { dispatch } = props;
    const res = await dispatch(USER_RESET_PASS(rows));
    console.log(res);
    if (res) {
      message.success('用户密码重置成功');
    }
  }

  const renderRightButton = () => {
    return (
      <>
        <Button>导入</Button>
        <Button>导出</Button>
      </>
    );
  }

  const code = 'user-list';
  const { userList, loading, total, addLoading, updateLoading, assignLoading, sexData, statusData } = props;
  const rowKey = (record: UserItem) => {
    return record.userId;
  }
  const pkField = 'userId';

  return (
    <PageContainer>
      <ProCard title="用户列表" headerBordered>
        <UserQueryForm
          colon={false}
          loading={loading}
          onSubmit={handleSubmitEx}
          onReset={handleReset}
        />
        <AGrid
          code={code}
          btnCallBack={handleBtnCallBack}
          renderLeftButton={renderLeftButton}
          renderRightButton={renderRightButton}
          columns={columns}
          rowKey={rowKey}
          pkField={pkField}
          dataSource={userList}
          loading={loading}
          total={total}
          onSelectRow={onSelectRow}
          onPageNumAndSizeChange={onPageNumAndSizeChange}
          scroll={{x:1600}}
          actionColumnFixed={'right'}
        />
      </ProCard>
      {
        !addModalVisible ? null :
        <AddUserModal
          colon={false}
          modalTitle='新增用户'
          modalWidth={1000}
          modalVisible={addModalVisible}
          loading={addLoading}
          sexData={sexData}
          statusData={statusData}
          onHandlerOK={handleAddModalOk}
          onHandlerCancel={handleAddModalCancel}
        />
      }
      {
        !updateModalVisible ? null :
        <UpdateUserModal
          colon={false}
          modalTitle=''
          modalWidth={1000}
          modalVisible={updateModalVisible}
          flag={flag}
          loading={updateLoading}
          formData={userFormData}
          sexData={sexData}
          statusData={statusData}
          onHandlerOK={handleUpdateModalOk}
          onHandlerCancel={handleUpdateModalCancel}
        />
      }
      {
        !assignRoleModalVisible ? null :
        <AssignRoleModal
          colon={false}
          modalTitle='分配角色'
          modalWidth={450}
          modalVisible={assignRoleModalVisible}
          loading={assignLoading}
          formData={roleFormData}
          onHandlerOK={handleAssignModalOk}
          onHandlerCancel={handleAssignModalCancel}
        />
      }
    </PageContainer>
  );
}

export default connect(({ users: {rows, ...res}, loading }: ConnectState) => ({
  ...res,
  userList: rows,
  loading: loading.effects['users/fetchAllUser'],
  addLoading: loading.effects['users/addUser'],
  updateLoading: loading.effects['users/updateUser'],
  previewLoading: loading.effects['users/fetchRolesByUser'],
  assignLoading: loading.effects['users/assignRolesToUser'],
}))(UserList);